#pragma once
#include<iostream>
#include<vector>
#include <semaphore.h>
#include <pthread.h>
#include<unistd.h>
#include "myLockGuard.hpp"
#define CUSTOMERNUM 3
#define PRODUCTORNUM 10
using namespace std;

const size_t g_cap=5;

template<class T>
class ringQueue
{
public:
    void P(sem_t& sem)//减少
    {
        sem_wait(&sem);
    }
    void V(sem_t& sem)//增加
    {
        sem_post(&sem);
    }
public:
    void pop(T& out)//消费者
    {
        //sleep(1);

        P(_customer_sem);
        pthread_mutex_lock(&_c_mutex);//单线程不需要加锁，多线程是为了维护消费者之间竞争关系

        out=_ring[_c_step++];//走到这步就说明一定申请资源成功
        _c_step%=_cap;
        pthread_mutex_unlock(&_c_mutex);

        V(_productor_sem);
    }
    void push(T& in)//生产者
    {

        P(_productor_sem);
        pthread_mutex_lock(&_p_mutex);//单线程不需要加锁，多线程是为了维护生产者之间竞争关系
        _ring[_p_step++]=in;//走到这步就说明一定申请资源成功
        _p_step%=_cap;
        pthread_mutex_unlock(&_p_mutex);

        V(_customer_sem);


    }
    ringQueue(int cap=g_cap)
    :_cap(cap)
    ,_ring(_cap)
    ,_c_step(0)
    ,_p_step(0)
    {
        sem_init(&_customer_sem,0,0);
        sem_init(&_productor_sem,0,_cap);
        pthread_mutex_init(&_c_mutex,nullptr);
        pthread_mutex_init(&_p_mutex,nullptr);
    }
    ~ringQueue()
    {
        sem_destroy(&_customer_sem);
        sem_destroy(&_productor_sem);
        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }

private:
    int _cap;
    vector<T> _ring;
    sem_t _customer_sem;
    sem_t _productor_sem;
    size_t _c_step;//生产者开始拿数据下标
    size_t _p_step;//消费者开始生产数据下标
    pthread_mutex_t _c_mutex;//生产者的锁
    pthread_mutex_t _p_mutex;//消费者的锁


};